from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from models.ChiTietDonHang import ChiTietDonHang
from models.HangDatHomNay import HangDatHomNay
from models.HangHoa import HangHoa
from utils.Const import TrangThaiDonHang
import datetime
import logging
import webapp2
from google.appengine.ext import db

logger = logging.getLogger("CronJob")

class OrderStatusHandler(webapp2.RequestHandler):
    def get(self):
        self.changeOrderStatus()
        self.response.out.write("Orders' status changed ")

    def changeOrderStatus(self):
        queryRemoveFailedDonHang = DaoQuanLyNhanVien.getListDonHangByStatus(TrangThaiDonHang.DANG_DAT_HANG)
        lstFailedDonHang = []
        for item in queryRemoveFailedDonHang:
            lstFailedDonHang.append(item)
        db.delete(lstFailedDonHang)
        
        queryDonHang = DaoQuanLyNhanVien.getListDonHangByStatus(TrangThaiDonHang.DA_DAT_HANG)
        lstIdDonHang = []
        lstDonHang = []
        for donHang in queryDonHang:
            donHang.trangThai = TrangThaiDonHang.KHOA
            lstDonHang.append(donHang)
            lstIdDonHang.append(donHang.key().id())
        
        lstHangHoa = []
        lstChiTietDonHang = []
        lstHangDatHomNay = []
        
        for i in range(0, lstIdDonHang.__len__()/30 + 1):
            queryChiTietDonHang = ChiTietDonHang.all().filter('maDonHang in', lstIdDonHang[i*30: (i+1)*30]).run()
            for ctdh in queryChiTietDonHang:
                lstChiTietDonHang.append(ctdh)
                lstHangHoa.append(HangHoa.get_by_id(ctdh.maHang))
        
        for hh in lstHangHoa:
            hangDat = HangDatHomNay()
            hangDat.maHang = hh.key().id()
            hangDat.tenHang = hh.tenHangHoa
            hangDat.soLuongTonKho = hh.soLuongTonKho
            hangDat.soLuongDat = 0.0
            hangDat.duTru = 0.0
            
            hangDat.ngay = (datetime.datetime.now() + datetime.timedelta(hours=7)).date()
            for ctdh in lstChiTietDonHang:
                if ctdh.duTru == None:
                    ctdh.duTru = 0.0
                if ctdh.maHang == hangDat.maHang:
                    hangDat.soLuongDat += ctdh.soLuong
                    hangDat.duTru += ctdh.duTru
                    lstChiTietDonHang.remove(ctdh)
            hh.soLuongTonKho += hangDat.duTru
            if hangDat.duTru > 0:
                lstDonHang.append(hh)
            if hangDat.soLuongDat > 0 or hangDat.duTru > 0:
                lstHangDatHomNay.append(hangDat)
        lstDonHang += lstHangDatHomNay
        db.put(lstDonHang)
        
            